package a05_双指针法;

import java.util.Arrays;


/**
 * <p>
 * a04_翻转字符串里的单词
 * </p>
 *
 * @author flyduck
 * @since 2024-07-17
 */
public class a04_翻转字符串里的单词复习1 {
    public static void main(String[] args) {
        System.out.println(reverseWords("the sky is blue"));
    }

    public static String reverseWords(String s) {
        char[] oldArray = s.toCharArray();
        //1、去除空格
        char[] newArray = removeExtraSpaces(oldArray);
        //2、整体反转
        reverse(newArray,0,newArray.length-1);
        //3、反转单词
        reverseEachWord(newArray);
        return new String(newArray);
    }

    private static void reverseEachWord(char[] newArray) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < newArray.length) {
            if(rightIdx == newArray.length - 1 || newArray[rightIdx + 1] == ' '){
                reverse(newArray, leftIdx, rightIdx);
                rightIdx = rightIdx + 2;
                leftIdx = rightIdx;
            }else {
                rightIdx++;
            }
        }
    }

    private static void reverse(char[] newArray, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx) {
            char temp = newArray[leftIdx];
            newArray[leftIdx] = newArray[rightIdx];
            newArray[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }


    private static char[] removeExtraSpaces(char[] oldArray) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldArray.length) {
            if(oldArray[fastIdx] != ' '){
                if(slowIdx != 0){
                    oldArray[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldArray.length && oldArray[fastIdx] != ' ') {
                    oldArray[slowIdx] = oldArray[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        char[] newArray = Arrays.copyOfRange(oldArray, 0, slowIdx);
        return newArray;
    }


}
